/* codebase:BlueStraggler http://blu.strglr.net
 * toolset:Feniseca       http://blu.strglr.net/Feniseca
 * package:hardcoded
 * file:fixer_script.groovy
 * 
 * Copyright 2011, 2012 Stellabs.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.strglr.blu.make;

// A class to facilitate the invocation of other groovy scripts
import groovy.util.GroovyScriptEngine;

public class Fixer {
    def GroovyScriptEngine engine;
    def facilities = [:];
    def Closure logClos = null;

    def Fixer(String scriptDir, Binding bind) {
        engine = new GroovyScriptEngine(scriptDir);
    };

    protected def loadFacility(String packageName, className, alias) {
        String scriptPath = packageName.replace('.', '/') + "/" + className + "_facility.groovy";
        Class clazz = engine.loadScriptByName(scriptPath);
        facilities.put(alias, clazz);
        if (logClos) logClos.call("" + this + ": Loaded facility '" + alias + "' ('" + scriptPath + "')");
        return clazz;
    };

    def getFacility(String packageName, String className, alias = "") {
        if (alias == "") alias = className;
        if (!facilities.containsKey(alias)) return loadFacility(packageName, className, alias);
        if (logClos) logClos.call("" + this + ": Searching class for facility '" + alias + "'");
        return facilities.get(alias);
    }

    def getFacility(alias) {
        if (logClos) logClos.call("" + this + ": Searching class for facility '" + alias + "'");
        assert facilities.containsKey(alias);
        return facilities.get(alias);
    }

    def setLog(clos) {
        if (logClos && !clos) logClos.call("" + this + ": Stopping Logging");
        logClos = clos;
        if (logClos) logClos.call("" + this + ": (Re)starting Logging");
    }

};

// Trick, -if loaded as a script- to get rid of "java.lang.InstantiationException: ..."
assert true;

// Must keep the following for the final evaluation
fixerInstantiator = { scriptPath, binding -> return new Fixer(scriptPath, binding); }
